//
//  ZHHomeController.swift
//  ZHWeibo
//
//  Created by user on 15/12/5.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

let HomeCellID = "HomeCellID"

class ZHHomeController: ZHVisitorController{

    
    var statusViewModel:ZHStatusViewModel? = ZHStatusViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        //加载数据
    }
    private func setUpUI() {
        
        vistorView?.setVistorInfo(nil, titleText: nil)
        if !isLogin {
            return
        }
        else{
            navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", title: nil, target: self, action: "findFriend")
            navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", title: nil, target: self, action: "")
            //初始化内部控件
            tableView.dataSource = self
            tableView.delegate = self
            //自动计算行高
            tableView.rowHeight = UITableViewAutomaticDimension
            //预估高度
            tableView.estimatedRowHeight = 200
            //去掉分割线
            tableView.separatorStyle = .None
            //注册单元格
            tableView.registerClass(ZHHomeViewCell.self, forCellReuseIdentifier: HomeCellID)
            
            loadHomeData()
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
 
    @objc private func findFriend() {
        let controller = ZHVisitorController()
        navigationController?.pushViewController(controller, animated: true)
    }
}

// MARK: - 数据源和代理
extension ZHHomeController {
    //加载微博数据
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (statusViewModel?.statusModel?.count) ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        /// 这里指定类型会报错,所以不能够指定类型,如果指定类型的话,后面必须使用as强转
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellID, forIndexPath: indexPath) as! ZHHomeViewCell
        cell.cellViewModel = statusViewModel?.statusModel![indexPath.row]
        return cell;
    }
}

// MARK: - 获取数据
extension ZHHomeController {
    //
    private func loadHomeData(){
        //请求数据的接口
        statusViewModel?.loadHomeData({ (isSuccess) -> () in
            if isSuccess {
                //刷新数据
                self.tableView.reloadData()
            }else{
                //请求数据错误
                SVProgressHUD.showErrorWithStatus("请求失败")
            }
        })
    }
}














